package com.qiange.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.qiange.common.Result;
import com.qiange.pojo.User;
import com.qiange.service.UserService;
import com.qiange.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;


    @PostMapping("/sendMsg")
    public Result<String> sendMsg(@RequestBody User user, HttpServletRequest request) {
        String phone = user.getPhone();
        if (StringUtils.isNotEmpty(phone)) {
            String code = ValidateCodeUtils.generateValidateCode(4).toString();
            log.info("验证码为{}", code);

//            request.getSession().setAttribute(phone, code);

            //把验证码添加到缓存redis中,代替session
            //
            redisTemplate.opsForValue().set(phone, code,60, TimeUnit.SECONDS);
            





            return Result.success("发送验证码成功");
        }

        return Result.error("手机号为空，发送验证码失败");
    }

    @PostMapping("/login")
    public Result<User> login(@RequestBody Map map) {
        String code = (String) map.get("code");
        String phone = (String) map.get("phone");

//        String msgCode = (String) request.getSession().getAttribute(phone);

        //从缓存中取出验证码，赋值给变量后删除redis缓存中的验证码
        String msgCode = (String) redisTemplate.opsForValue().get(phone);
        redisTemplate.delete(phone);

        if (msgCode != null && msgCode.equals(code)) {
            LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper();
            lqw.eq(User::getPhone, phone);

            User user = userService.getOne(lqw);
            if (user == null) {
                user = new User();
                user.setPhone(phone);
                user.setStatus(1);
                userService.save(user);
            }

//            request.getSession().setAttribute("user",user.getId());

            redisTemplate.opsForValue().set("user", user.getId());

            return Result.success(user);
        }

        return Result.error("验证码错误");
    }

    @PostMapping("/loginout")
    public Result<String> loginout(/*HttpSession session*/) {
//        session.removeAttribute("user");

        redisTemplate.delete("user");
        return Result.success("退出成功");
    }
}
